package com.hmall.common.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(
        prefix = "spring.rabbitmq.listener.simple.retry",
        name = "enabled",
        havingValue = "true"
)
public class MyConsumerErrorAutoConfig {

    @Value("${spring.application.name}")
    private String applicationName;

    @Bean
    public DirectExchange errorDirectExchange() {
        return new DirectExchange("error.direct");
    }

    @Bean
    public Queue errorQueue(){
        String queueName = applicationName + ".error.queue";
        return new Queue(queueName, true);
    }

    @Bean
    public Binding errorQueueBinding(DirectExchange errorDirectExchange, Queue errorQueue) {
        return BindingBuilder.bind(errorQueue).to(errorDirectExchange).with(applicationName);
    }

    @Bean
    public RepublishMessageRecoverer messageRecover(RabbitTemplate rabbitTemplate, DirectExchange errorDirectExchange) {
        return new RepublishMessageRecoverer(rabbitTemplate, errorDirectExchange.getName(), applicationName);
    }
}

